import getUserTempId from "@/utils/userTempId";
import { requestLogin, requestUserInfo, requestLogout } from "@/api";
const state = {
  userTempId: getUserTempId(),
  token: localStorage.getItem("user_Token") || "",
  nickName: "",
};
const mutations = {
  SET_TOKEN_STATE(state, value) {
    state.token = value;
  },
  SET_USERNAME_STATE(state, username) {
    state.nickName = username;
  },
  SET_LOGOUT_STATE(state) {
    state.token = "";
    state.nickName = "";
    localStorage.removeItem("user_Token");
  },
};
// 这个请求是异步的 
const actions = {
  async getLogin({ commit }, userInfo) {
    const result = await requestLogin(userInfo);
    console.log(result);
      //拿到token和用户的临时标识
    commit("SET_TOKEN_STATE", result.token);
    //请求到token之后,要把token持久化到本地中,否则刷新以后vuex就没有数据了,用户需要重新登录
    localStorage.setItem("user_Token", result.token);
  },

  async getUserName({ commit }) {
    const result = await requestUserInfo();
    console.log(result);
    commit("SET_USERNAME_STATE", result.nickName);
  },

  //退出登录
  async getLogout({ commit }) {
    await requestLogout();
    commit("SET_LOGOUT_STATE");
  },
};
const getters = {};
export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters,
};
